package top.carrotguo.weibo.presenter;

import java.lang.ref.WeakReference;

import top.carrotguo.weibo.view.IView;

/**
 * Presenter生命周期包装、View的绑定和解除，P层实现的基类
 * Created by carrot on 2018-10-10.
 */

public class BasePresenter<V extends IView> implements IPresenter<V>{

    //弱引用来引用视图，避免presenter持有已经被回收的view
    private WeakReference<V> mViewRef;

    /**
     * 获取view实例
     * @return view
     */
    public V getView(){
        return mViewRef.get();
    }

    @Override
    public void attachView(V view) {
        mViewRef = new WeakReference<V>(view);
    }

    @Override
    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }

    /**
     * 判断view是否绑定
     * @return
     */
    public boolean isViewAttached(){
        return mViewRef!=null && mViewRef.get()!=null;
    }
}
